package com.java2nb.novel.pay.controller;

import com.java2nb.novel.pay.common.SignUtils;
import com.java2nb.novel.pay.vo.PayOrderResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    // 默认私钥（实际应从商户配置获取，此处为演示）
    private static final String DEFAULT_SECRET_KEY = "default_secret_key";

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public PayOrderResponseVO handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 获取第一个校验失败的消息
        String errorMsg = e.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
        log.error("参数校验失败：{}", errorMsg, e);

        PayOrderResponseVO response = new PayOrderResponseVO();
        response.setCode("9999");
        response.setMsg("参数错误：" + errorMsg);
        return signResponse(response);
    }

    /**
     * 处理通用异常
     */
    @ExceptionHandler(Exception.class)
    public PayOrderResponseVO handleException(Exception e) {
        log.error("系统异常：", e);

        PayOrderResponseVO response = new PayOrderResponseVO();
        response.setCode("9999");
        response.setMsg("系统异常，请联系管理员");
        return signResponse(response);
    }

    /**
     * 响应签名（演示用，实际应传入商户私钥）
     */
    private PayOrderResponseVO signResponse(PayOrderResponseVO response) {
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("code", response.getCode());
        responseMap.put("msg", response.getMsg());
        responseMap.put("signType", response.getSignType());

        String sign = SignUtils.generateSign(responseMap, DEFAULT_SECRET_KEY);
        response.setSign(sign);
        return response;
    }
}
